<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { ArrowLeft } from '@element-plus/icons-vue'
import { Api } from '@/api'
import ArticleEdit from './components/ArticleEdit.vue'

const router = useRouter()
const loading = ref(false)
const articles = ref([])

// 返回上一页
const goBack = () => {
  router.back()
}

// 格式化文章内容
const formatContent = (content) => {
  if (!content) return ''
  // 移除HTML标签
  const plainText = content.replace(/<[^>]+>/g, '')
  // 限制显示长度
  return plainText.length > 100 ? plainText.slice(0, 100) + '...' : plainText
}

// 获取文章列表
const loadArticles = async () => {
  try {
    loading.value = true
    const response = await Api.getPsychologyKnowledgeList()
    if (response.data && Array.isArray(response.data.data)) {
      articles.value = response.data.data
    }
  } catch (err) {
    console.error('加载文章列表失败:', err)
    ElMessage.error('加载文章列表失败')
  } finally {
    loading.value = false
  }
}

// 删除文章
const handleDeleteArticle = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    await Api.deletePsychologyKnowledge({ id })
    ElMessage.success('删除成功')
    loadArticles()
  } catch (err) {
    if (err !== 'cancel') {
      console.error('删除失败:', err)
      ElMessage.error('删除失败')
    }
  }
}

// 编辑文章
const articleEditRef = ref()
const handleEditArticle = (article) => {
  articleEditRef.value.open(article.id)
}

// 添加文章
const handleAddArticle = () => {
  articleEditRef.value.open()
}

// 编辑成功回调
const onEditSuccess = () => {
  loadArticles()
}

onMounted(() => {
  loadArticles()
})
</script>

<template>
  <div class="article-manage">
    <!-- 返回按钮 -->
    <div class="back-button" @click="goBack">
      <el-icon><ArrowLeft /></el-icon>
      返回
    </div>

    <h1>心理知识管理</h1>

    <div class="toolbar">
      <div class="toolbar-right">
        <el-button type="primary" @click="handleAddArticle">添加文章</el-button>
      </div>
    </div>

    <el-table :data="articles" v-loading="loading" border>
      <el-table-column prop="title" label="文章标题" />
      <el-table-column label="文章内容" :show-overflow-tooltip="true">
        <template #default="{ row }">
          <span>{{ formatContent(row.content) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <div class="button-group">
            <el-button
              type="primary"
              size="small"
              @click="handleEditArticle(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="() => handleDeleteArticle(row.id)"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 文章编辑组件 -->
    <article-edit
      ref="articleEditRef"
      @success="onEditSuccess"
    />
  </div>
</template>

<style scoped>
.article-manage {
  padding: 20px;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 16px;
  color: #409EFF;
  font-weight: bold;
  margin-bottom: 20px;
  transition: color 0.3s ease;
}

.back-button:hover {
  color: #66b1ff;
}

.back-button .el-icon {
  font-size: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.toolbar-right {
  display: flex;
  gap: 10px;
}

h1 {
  margin-bottom: 20px;
  color: #333;
}

.button-group {
  display: flex;
  gap: 8px;
  justify-content: center;
}
</style>
